package cn.myframe;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/*******************
 *@Describe 持久化消息订阅
 *@author 封神梦
 *@Time 2022/8/2
 *@Company http://com.yiview.com
 ****************/
public class DurableSubscriberDemo {
    public static void main(String[] args) {
        try{
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");

            //2.创建连接
            Connection connection = connectionFactory.createConnection();

            connection.setClientID("fsm");
            //3.启动连接
            connection.start();

            //4.获取session(会话对象)
    /*
    arg0 是否启用事务
    arg1 消息的确认方式 自动确认
     */
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            //5、如主题不存在创建主题
            Topic topic = session.createTopic("first-topic");

            //6.创建消息消费者对象
            TopicSubscriber consumer = session.createDurableSubscriber(topic,"fsm");

            //7.设置监听
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    TextMessage textMessage = (TextMessage)message;
                    try {
                        System.out.println("提取的消息是=====>"+textMessage.getText());
                        message.acknowledge();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });
            //8.等待键盘输入
            //目的是为了让程序停止来看效果
            System.in.read();
            //9.关闭资源
            consumer.close();
            session.close();
            connection.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
